import React, { Component } from "react";
import { connect } from "dva";
import { routerRedux } from "dva/router";
import { Card, Button, Icon, Input, message, Tag } from "antd";
import MarkdownEditor from "@/utils/vditor";
import RelatedKnowledgeTag from "@/utils/RelatedKnowledgeTag";
import { addFile, editFile, getFileInfo } from "@/services/knowledgeFile";

let timer;
class AddFile extends Component {
	constructor(props) {
		super(props);
		this.state = {
			isShowTitle: false,
			content: '',
			title: '',
			fileTitle: '',
			btnLoading: false,
			knowledgeTagList: [],
			relatedTagVisible: false,
			pageHeight: 0,
			isPageHeight: false,
		};
	}

	componentDidMount() {
		const { location: { query } } = this.props;
		if (query.id) {
			this.info(query.id);
		};
		timer = setTimeout(() => {
			this.getPageHeight()
		}, 500)
		window.addEventListener('resize', this.getPageHeight)
	}

	componentWillUnmount() {
		timer && clearTimeout(timer);
		window.removeEventListener('resize', this.getPageHeight)
	}

	getPageHeight = () => {
		if(document.getElementById('color_tag_file')) {
			console.log(document.getElementById('color_tag_file').clientHeight);
			this.setState({ pageHeight: document.getElementById('color_tag_file').clientHeight - 76 })
		}
	}

	info = async id => {
		let res = await getFileInfo({ id });
		let knowledgeTagList = [];
		if (res.tagTypeList && res.tagTypeList.length) {
			res.tagTypeList.forEach(item => {
				if (item.tagList && item.tagList.length > 0) {
					item.tagList.forEach(i => {
						knowledgeTagList.push({ color: item.tagColor, id: i.id, name: i.tagValue })
					})
				}
			});
		};
		this.setState({
			title: res.docName,
			knowledgeTagList,
			// fileTitle: res.docContent.match(/\n(?:[^\n])*/g)[0].replace(/\n/gi, ''),
			// content: res.docContent.slice(this.getStrHtml(res.docContent).length, -1),
			fileTitle: res.docTitle,
			content: res.docContent,
		})
	}

	getStr(str) {
		return str.match(/\n(?:[^\n])*/g, function (s) {
			return s;
		})
	}

	getStrHtml = (str) => {
		var v = (this.getStr(str)[0].replace(/\n(([\w])+)?n/g, function ($1, $2) {
			return $2;
		}).split(" "))[0];

		return this.getStr(str)[0] + "/n"
	}

	backRouter = () => {
		this.getKnowledgeFileList();
	}

	setTitle = e => {
		this.setState({ title: e.target.value })
	}

	save = () => {
		const { match: { params: { id }, }, route, location: { params, query } } = this.props;
		const { title, content, fileTitle, knowledgeTagList } = this.state;
		if (!title || title == '') {
			return message.error('请输入文件名')
		};
		if (!fileTitle || fileTitle === '') {
			return message.error('请输入文件标题')
		};
		if (!content || content === '' || content == '\n') {
			return message.error('请输入文件内容')
		};
		let obj = {
			rootCategoryId: id,
			categoryId: query.fileCategoryId,
			categoryPath: query.fileCategoryPath,
			docName: title,
			docTitle: fileTitle,
			docContent: content,
			knowledgeTagList: knowledgeTagList.map(i => i.id),
		};
		this.setState({ btnLoading: true }, async () => {
			if (query.id) {
				obj.id = query.id;
				let res = await editFile(obj);
				// console.log(res);
				if (res.code == 0) {
					message.info(res.msg);
					this.setState({ btnLoading: false });
				} else {
					this.setState({ btnLoading: false });
				}
			} else {
				let res = await addFile(obj);
				// console.log(res);
				if (res.code == 0) {
					message.info(res.msg);
					this.getKnowledgeFileList();
					this.setState({ btnLoading: false });
				} else {
					this.setState({ btnLoading: false });
				}
			}
		})
	}

	// 新增自定义文档
	getKnowledgeFileList = () => {
		const { match: { params: { id }, }, location: { query }, dispatch } = this.props;
		let pathname = "/knowledgeDesign/myKnowledge/" + id + "/file";
		dispatch(routerRedux.push({ pathname, query: { fileCategoryId: query.fileCategoryId } }));
	}

	render() {
		const { match: { params: { id }, }, route, location: { params, query } } = this.props;
		const { isShowTitle, title, btnLoading, knowledgeTagList, relatedTagVisible, pageHeight, isPageHeight } = this.state;

		return (
			<Card bordered={false}>
				<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', margin: '-8px 0 16px' }}>
					<div style={{ fontWeight: 'bold', fontSize: '15px' }}>
						{query.id ? (
							isShowTitle ? (
								<Input placeholder="请输入文档名称" value={title} onChange={e => this.setTitle(e)} />
							) : (
								<>
									<span>{title}</span>
									<Icon type="edit" style={{ marginLeft: 6 }} onClick={() => this.setState({ isShowTitle: true })} />
								</>
							)
						) : (
							<Input placeholder="请输入文档名称" value={title} onChange={e => this.setTitle(e)} />
						)}
					</div>
					<div>
						<Button
							onClick={() => this.openRelatedKnowledgeTagModal()}
							style={{
								backgroundColor: "#FFFFFF",
								color: '#3E5BFF',
								borderColor: '#6478FF',
								// borderRadius: '16px',
								marginRight: 10
							}}
						>
							添加知识标签
						</Button>
						<Button type="primary" style={{ marginRight: 10 }} onClick={this.save} loading={btnLoading}>保存</Button>
						<Button onClick={this.backRouter} icon="arrow-left">返回</Button>
					</div>
				</div>
				{knowledgeTagList && knowledgeTagList.length > 0 ? (
					<div style={{ marginBottom: 20, display: 'flex', position: 'relative' }}>
						<div style={{ maxHeight: isPageHeight ? 'unset' : '76px', overflow: 'hidden', flex: 1 }}>
							<span id="color_tag_file" style={{ display: 'flex', flexFlow: 'wrap', gap: '12px', }}>
								<span style={{ lineHeight: '32px', fontWeight: 'bold', fontSize: '14px' }}>关联知识标签：</span>
								{knowledgeTagList.map((item, index) => {
									return (
										<>
											{item.color == '#FFF' || item.color == '#FFFFFF' || item.color == '' ? (
												<Tag
													key={index}
													color={item.color}
													style={{
														padding: '5px 12px',
														fontSize: '14px',
														margin: 0,
														color: item.color + '99',
														background: item.color + '1A',
														// border: '1px solid '+ item.color,
													}}
												>
													<span>{item.name}</span>
													<Icon
														type="close"
														style={{
															color: item.color + '99',
															marginLeft: 8,
														}}
														onClick={() => this.removeRelatedTagData(item)}
													/>
												</Tag>
											) : (
												<Tag
													key={index}
													color={item.color}
													style={{
														padding: '5px 12px',
														fontSize: '14px',
														margin: 0,
														color: item.color + '99',
														background: item.color + '1A',
														// border: '1px solid '+ item.color,
													}}
												>
													<span>{item.name}</span>
													<Icon
														type="close"
														style={{
															color: item.color + '99',
															marginLeft: 8,
														}}
														onClick={() => this.removeRelatedTagData(item)}
													/>
												</Tag>
											)}
										</>
									)
								})}
							</span>
						</div>
						{pageHeight && pageHeight > 0 ? (
							<div style={{ width: '60px' }}>
								<Button
									type="link"
									style={{ position: 'absolute', bottom: '0px', right: '0px', }}
									onClick={() => this.setState({ isPageHeight: !isPageHeight })}
								>
									{isPageHeight ? '收起' : '全部' }
								</Button>
							</div>
						) : null}
					</div>
				) : null}
				<MarkdownEditor
					value={this.state.content}
					title={this.state.fileTitle}
					name='markdown-editor'
					id='markdown-editor'
					height='calc(100vh - 250px)'
					width='700'
					onChange={(value, type) => {
						switch (type) {
							case 'content':
								this.setState({ content: value });
								break;
							case 'title':
								this.setState({ fileTitle: value });
								break;
						}
					}}
					ref={(r) => (this.vEditor = r)}
				/>
				<RelatedKnowledgeTag
					visible={relatedTagVisible}
					onClose={this.closeRelatedTagModal}
					getRelatedList={this.getRelatedTagList}
					onRef={(ref) => (this.RelatedKnowledgeTag = ref)}
				/>
			</Card>
		);
	}


	/**
	 * 关联知识标签
	 * @param data
	 * @returns {*}
	 */
	openRelatedKnowledgeTagModal = () => {
		let { knowledgeTagList } = this.state;
		this.RelatedKnowledgeTag.getList(knowledgeTagList);
		this.setState({ relatedTagVisible: true, });
	};

	closeRelatedTagModal = () => {
		this.setState({ relatedTagVisible: false, });
	};

	getRelatedTagList = (data) => {
		this.setState({ knowledgeTagList: data, });
	};

	removeRelatedTagData = (tag) => {
		let { knowledgeTagList } = this.state;
		const newData = knowledgeTagList.filter(item => item != tag);
		this.setState({ knowledgeTagList: newData });
	};
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(AddFile);
